# -*- coding:utf-8 -*-
import os
import time
import sys
import random
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from AddTask import AddWindow
from DBhandler import ADhandler
from Element import ElementWidget

class TaskList(QListWidget):
    data_Signal = pyqtSignal(dict)

    def __init__(self,btn_index_map):
        super(TaskList, self).__init__()
        self.btn_index_map = btn_index_map
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.right_menu)
        self.itemClicked.connect(self._emit_data)
        self.color_list = ['#e1f3f9','#e5ddf3','#faf7eb','#faeee5','#fde8eb','#f4fde8','#e8fdf9',
                           '#e4f7e6','#f4f7e4','#eee4f7']

    def _conver_date(self,utime):
        """
        将时间戳转成日期
        :param utime:
        :return:
        """

        ttime = time.localtime(utime)
        time_date = time.strftime("%Y-%m-%d %H:%M:%S", ttime)
        return time_date

    def set_tasks(self,data_list):
        """
        添加任务item
        :param data_list:
        :return:
        """
        self.clear()
        if data_list:
            sorted_data_list = sorted(data_list,key=lambda x:x['_id'],reverse=True)
            for data in sorted_data_list:
                deleta_hour = round((data['_end_time'] - int(time.time()))/3600.0,2)
                _pub_date = self._conver_date(data['_pub_time'])
                item_widget = ElementWidget(data['_title'],data['_name'],_pub_date,deleta_hour)
                item = QListWidgetItem()
                item.setSizeHint(QSize(150,80))
                color = self.color_list[random.randint(0,len(self.color_list)-1)]
                item.setBackground(QColor(color))

                item.setData(5,data)
                self.addItem(item)
                self.setItemWidget(item,item_widget)


    def right_menu(self):
        rMenu = QMenu()
        addAction = QAction('发布任务',self)
        addAction.triggered.connect(self.add_task)
        rMenu.addAction(addAction)
        rMenu.exec_(QCursor.pos())

    def add_task(self):
        print('发布任务')
        self.add_window = AddWindow(self.btn_index_map)
        self.add_window.show()

    def _emit_data(self,item):
        self.data_Signal.emit(item.data(5))


class AD(QWidget):

    def __init__(self):
        super(AD, self).__init__()
        self.btn_style = '''QToolButton{color:black}
                                  QToolButton:hover{color:#FF7F24}
                                  QToolButton{background-color:#CFCFCF}
                                  QToolButton{border:2px}
                                  QToolButton{border-radius:10px}
                                  QToolButton{padding:5px 1px}'''

        self._select_btn_style = '''QToolButton{color:#FF7F24}
                                  QToolButton:hover{color:#FF7F24}
                                  QToolButton{background-color:#CFCFCF}
                                  QToolButton{border:2px}
                                  QToolButton{border-radius:10px}
                                  QToolButton{padding:5px 1px}'''


        self._help = "操作说明：\n\n" \
                     "1.点击对应模块可切换到当前模板信息栏\n\n" \
                     "2.点击列表标题显示具体内容\n\n" \
                     "3.右键列表可以发布任务。\n\n" \
                     "注意：\n\n" \
                     "任务除了自己透露的信息外\n" \
                     "发布不留痕迹！\n" \
                     "不可查询来源！\n" \
                     "不可手动删除修改！\n" \
                     "只会在自己设定的任务时间到期后自动销毁"

        self.btn_map = {0:'合租转租',1:'宠物',2:'寻物/失物',3:'二手交易',4:'技术交流',
                        5:'游戏开黑',6:'活动娱乐',7:'吐槽搞事',8:'其他'}

        self.db_handler = ADhandler()

        self.btn_index_map = dict((v,k) for k,v in self.btn_map.items())
        self.text_font = QFont('', 10, 35)
        self.current_type = None
        self.btn_list = []
        self.icon = QIcon()
        self.icon.addPixmap(QPixmap('ad.png'))
        self.setWindowIcon(self.icon)
        self.setWindowTitle('广告栏')
        self.main_layout = QVBoxLayout()
        self.choose_btn_layout = QHBoxLayout()
        self.init_choose_btns(self.btn_map)

        self.sp = QSplitter(Qt.Vertical)
        self.show_list = TaskList(self.btn_index_map)
        self.show_list.data_Signal.connect(self._show_data)
        self.show_text = QTextBrowser()
        self.show_text.setText(self._help)
        self.show_text.setFont(self.text_font)
        self.sp.addWidget(self.show_list)
        self.sp.addWidget(self.show_text)
        self.sp.setStretchFactor(0,7)
        self.sp.setStretchFactor(1,3)


        self.main_layout.addLayout(self.choose_btn_layout)
        self.main_layout.addWidget(self.sp)


        self.setLayout(self.main_layout)


    def init_choose_btns(self,btn_map):
        if btn_map:
            keys = sorted(btn_map.keys())
            for k in keys:
                btn_name = btn_map[k]
                toolbtn = QToolButton()
                toolbtn.setText(btn_name)
                toolbtn.setStyleSheet(self.btn_style)
                toolbtn.clicked.connect(self._choose)
                self.btn_list.append(toolbtn)
                self.choose_btn_layout.addWidget(toolbtn)

    def _choose(self):
        self.show_list.clear()
        self.show_text.setText(self._help)
        btn = self.sender()
        self.set_btn_color(btn)
        self.current_type = self.btn_index_map.get(btn.text(),None)
        data_list = self.db_handler.get_data(self.current_type)
        print(data_list)
        try:
            self.show_list.set_tasks(data_list)
        except Exception as set_tasks_ERR:
            print('set_tasks_ERR:',str(set_tasks_ERR))

    def set_btn_color(self,btn):
        for i in self.btn_list:
            if i == btn:
                i.setStyleSheet(self._select_btn_style)
            else:
                i.setStyleSheet(self.btn_style)


    def _show_data(self,data):
        self.show_text.clear()
        self.show_text.setText(data['_text'])


if __name__ == '__main__':
    app = QApplication(sys.argv)
    a = AD()
    a.show()
    sys.exit(app.exec_())







